/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.common.util;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;

import com.google.inject.Singleton;
 

/**
 * Utility class for handling workspace and EMF resources.
 *
 * @author Thomas Kistel
 * @version $Revision: 758 $
 */
@Singleton
public class ResourcesUtil {
    
    /**
     * Returns the project that contains the resource at the given URI.
     * 
     * @param resourceUri the given URI.
     * @return the project that contains the resource at the given URI, or {@code null} if the resource at the
     *         given URI is not in a workspace.
     */
    public IProject project(URI resourceUri) {
        IFile file = file(resourceUri);
        return (file != null) ? file.getProject() : null;
    }

    /**
     * Indicates whether the given URI belongs to an existing file.
     * 
     * @param fileUri the URI to check, as a {@code String}.
     * @return {@code true} if the given URI belongs to an existing file, {@code false} otherwise.
     */
    public boolean fileExists(URI fileUri) {
        IFile file = file(fileUri);
        return (file != null) ? file.exists() : false;
    }

    /**
     * Returns a handle to a workspace file identified by the given URI.
     * 
     * @param uri the given URI.
     * @return a handle to a workspace file identified by the given URI or {@code null} if the URI does not
     *         belong to a workspace file.
     */
    public IFile file(URI uri) {
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IPath path = pathOf(uri);
        return (path != null) ? root.getFile(path) : null;
    }

    /**
     * Finds the resource with the given <code>targetName</code>, which must be located in the same
     * directory as the given <code>source</code> URI.
     * 
     * @param source the source URI which must point to a file
     * @param targetName the name of the target file which must be in the same directory as the the source
     * @return the URI of the target file or <code>null</code> if it was not found
     * @throws CoreException if the member of the source cannot be retrieved.
     */
    public URI findResource(final URI source, final String targetName) throws CoreException {
        IFile sourceFile = file(source);
        IContainer folder = sourceFile.getParent();
        folder.getFile(new Path(targetName));
        ResourceVisitor visitor = new ResourceVisitor(targetName);
        folder.accept(visitor, IResource.DEPTH_ONE, IContainer.DO_NOT_CHECK_EXISTENCE | IContainer.INCLUDE_PHANTOMS);
        IPath path = visitor.getPath();
        if(path != null) {
            URI uri = URI.createPlatformResourceURI(path.toString(), true);
            return uri;
        }
        return null;
    }
    
    private IPath pathOf(URI uri) {
        String platformUri = uri.toPlatformString(true);
        return (platformUri != null) ? new Path(platformUri) : null;
    }
    
    /**
     * Internal Visitor class to retrieve a IPath for a given targetName.
     */
    private static class ResourceVisitor implements IResourceProxyVisitor {
        
        private final String targetName;
        private IPath path;
        
        public ResourceVisitor(String targetName) {
            this.targetName = targetName;
        }
        

        @Override
        public boolean visit(IResourceProxy proxy) throws CoreException {
            if(path == null && proxy.isAccessible() && proxy.getName().equals(targetName)) {
                path = proxy.requestFullPath();
                return false;
            }
            return true;
        }
        
        public IPath getPath() {
            return path;
        }
    }
}
